import React, { useEffect, useState, useRef } from 'react'
import { Map, extent , proj } from 'ol'; 
import { View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import WMS from 'ol/source/TileWMS';
import LayerGroup from 'ol/layer/Group';
import Draw, {
	createBox
} from 'ol/interaction/Draw';


import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';

import ReactDom from 'react-dom';
import Draggable from 'react-draggable';

import { getRenderPixel } from 'ol/render';
import WMTS, { optionsFromCapabilities } from 'ol/source/WMTS';
import WMTSCapabilities from 'ol/format/WMTSCapabilities';
import Feature from 'ol/Feature';
import GeoJSON from 'ol/format/GeoJSON';

import * as olProj from 'ol/proj';
import * as olExtent from 'ol/extent';
import Overlay from 'ol/Overlay';
import {fromLonLat, toLonLat} from 'ol/proj';

import './MapPanel.css';
import {Style,Fill,Stroke} from 'ol/style';
import dayjs from 'dayjs';

import proj4 from 'proj4' ;
import {get as getProjection} from 'ol/proj.js' ;
import {register } from 'ol/proj/proj4.js' ;

//全局变量，用于保存卷帘滑块的中心位置x坐标
var g_draggerCenterX = -1;
var g_isInSwipeCompareMode = false; // 0 or 1
var g_MapPanel_mtbcmd = '' ;
var g_MapPanel_olMap = null ;
var g_MapPanel_olMapLayerGroupA = null ;
var g_MapPanel_olMapLayerGroupB = null ;
var g_MapPanel_updatePinPopupTextFunc = null ;
var g_MapPanel_pinboxOverlay = null ;
const viewWidth = window.innerWidth;
const viewHeight = window.innerHeight;
const draggerWidth = 56;
const draggerHeight = 56;
var g_MapPanel_groupAArray = [] ;
var g_MapPanel_groupBArray = [] ;
var g_MapPanel_appDateA = null;
var g_MapPanel_appDateB = null ;



//GroupB Prerender event
const g_onGroupBPrerenderCallback = function (event) {
	const ctx = event.context;
	ctx.save();
	ctx.beginPath();
	ctx.moveTo(g_draggerCenterX, 0);
	ctx.lineTo(g_draggerCenterX, viewHeight);
	ctx.lineTo(viewWidth, viewHeight);
	ctx.lineTo(viewWidth, 0);
	ctx.closePath();
	ctx.clip();
}
//GroupB Postrender event
const g_onGroupBPostrenderCallback = function (event) {
	const ctx = event.context;
	ctx.restore();
}

//GroupA Prerender event
const g_onGroupAPrerenderCallback = function (event) {
	const ctx = event.context;
	ctx.save();
	ctx.beginPath();
	ctx.moveTo(0, 0);
	ctx.lineTo(0, viewHeight);
	ctx.lineTo(g_draggerCenterX, viewHeight);
	ctx.lineTo(g_draggerCenterX, 0);
	ctx.closePath();
	ctx.clip();
}

//GroupA Postrender event
const g_onGroupAPostrenderCallback = function (event) {
	const ctx = event.context;
	ctx.restore();
}

//从图层参数列表中找到最顶层Visible为true的图层参数 2022-5-18
//如果arr为空，返回null
const g_getTopMostLayerParamsFromArray = function( arr ){
	if( typeof arr ==='undefined' || arr===null || arr.length===0 ){
		return null ;
	}
	let out1 = null ;
	for(let i = 0 ; i<arr.length;++i ){
		if(arr[i].visible===true){
			if( out1===null ) out1 = arr[i] ;
			else{
				if( out1.zindex < arr[i].zindex ) out1 = arr[i] ;
			}
		}
		
	}
	return out1 ;
}



//使用图层ID查找在Openlayer图层组中的图层对象
const g_helperFindLayerObjInOlMapByDisplayid = function (isInA , displayid) {
	let lyrGroup =  g_MapPanel_olMapLayerGroupA ;
	if( isInA===false ) lyrGroup = g_MapPanel_olMapLayerGroupB ;
	if (lyrGroup!==null && lyrGroup.getLayers() !== null) {
		const temparr = lyrGroup.getLayers().getArray();
		for (let i = 0; i < temparr.length; ++i) {
			const lyrItem = temparr[i];
			if ( lyrItem.displayid === displayid ) {
				return lyrItem;
			}
		}
	}
	return null;
}


//js Date 对象转Long型 YYYYMMDD000000 数据，注意目前时分秒使用0代替。
const g_MapPanel_convertJsDate2Ymd14 = function (jsDate) {
	const dayjsdate = dayjs(jsDate);
	const datetime1 = dayjsdate.format("YYYYMMDD000000");
	return datetime1;
}


//地图点击事件，获取远端像素值
const g_onMapSingleClickedFunc = function(event) {

	if( g_MapPanel_mtbcmd === 'pin')
	{
		g_MapPanel_updatePinPopupTextFunc("Ready") ;
		g_MapPanel_pinboxOverlay.setPosition(event.coordinate) ;
		let pixelx = event.pixel[0] ;
		let pixely = event.pixel[1] ;

		let lon1 = event.coordinate[0] ;
		let lat1 = event.coordinate[1] ;

		//判断是否对比模式，如果对比模式判断是在A还是在B
		let isInA = true ;
		if( g_isInSwipeCompareMode===true ){
			if( pixelx > g_draggerCenterX ){
				isInA = false ;
			}
		}

		//找到最顶层图层，如果是pe,ud,pes,us调用后台程序获取像素值，如果是wms图层获取RGB值
		let topMostLyrParams = null ;
		if( isInA===true ){
			topMostLyrParams = g_getTopMostLayerParamsFromArray(g_MapPanel_groupAArray) ;
		}else{
			topMostLyrParams = g_getTopMostLayerParamsFromArray(g_MapPanel_groupBArray) ;
		}

		let datetime1 = g_MapPanel_convertJsDate2Ymd14(g_MapPanel_appDateA) ;
        if( isInA===false ){
            datetime1 = g_MapPanel_convertJsDate2Ymd14(g_MapPanel_appDateB) ;
        }

		if( topMostLyrParams!==null ){
			const lyrInOlMap = g_helperFindLayerObjInOlMapByDisplayid(isInA, topMostLyrParams.displayid) ;
			if( lyrInOlMap!==null )
			{
				let tPinText = topMostLyrParams.productDisplay.productname ;
				tPinText+='\n经度:'+event.coordinate[0].toFixed(3)+",纬度:"+event.coordinate[1].toFixed(3) ;
				if(topMostLyrParams.productDisplay.type === 'pes' 
				|| topMostLyrParams.productDisplay.type === 'us'
				|| topMostLyrParams.productDisplay.type === 'ud'
				|| topMostLyrParams.productDisplay.type === 'pe' )
				{
					let url1 = "" ;
					let sduistr = "null" ;
					if (typeof topMostLyrParams.sdui !== 'undefined'
					 && topMostLyrParams.sdui !== null) {
						let slimSdui = {};
						for (let key in topMostLyrParams.sdui) {
							slimSdui[key] = { val: topMostLyrParams.sdui[key].val };
						}
						sduistr = encodeURIComponent( JSON.stringify(slimSdui) );
					}

					if(topMostLyrParams.productDisplay.type === 'pes')
					{
						let t_pdtdisplayParams = JSON.parse(topMostLyrParams.productDisplay.params);
						let t_sid = t_pdtdisplayParams.sid;
						url1 = global.g_serverAPIRoot + "scripts/pixvals/?sid="
							+ t_sid 
							+ "&lon="+lon1 + "&lat=" + lat1 
							+ "&datetime=" + datetime1
							+ "&sdui=" + sduistr 
							+ "&utime=" + Date.now(); ;
					}else if(topMostLyrParams.productDisplay.type === 'us'){
						url1 = global.g_serverAPIRoot + "scripts/pixvals/?sid="
						+ topMostLyrParams.sid 
						+ "&lon="+lon1 + "&lat=" + lat1 
						+ "&datetime=" + datetime1
						+ "&sdui=" + sduistr 
						+ "&utime=" + Date.now(); ;
					}else {
						//pe and ud
						url1 = global.g_serverAPIRoot + "product/pixvals/?"
						+"pid=" + topMostLyrParams.pid
						+"&lon="+lon1 + "&lat=" + lat1 
						+"&datetime=" + datetime1 ;
					}
					fetch(url1)  //GET
					.then(response=>response.json())
					.then(result => {
						if( result.state===0 ){
							for(let i1 = 0 ;i1 < result.data.length;++i1){
								tPinText+='\n'+result.data[i1] ;
							}
							if( g_MapPanel_updatePinPopupTextFunc!==null){
								g_MapPanel_updatePinPopupTextFunc(tPinText) ;
							}
						}else{
							tPinText += "\n出错了:"+result.message ;
							if( g_MapPanel_updatePinPopupTextFunc!==null){
								g_MapPanel_updatePinPopupTextFunc(tPinText) ;
							}
						}
					}).catch(err=> {
						tPinText += "\n出错了:"+err ;
						if( g_MapPanel_updatePinPopupTextFunc!==null){
							g_MapPanel_updatePinPopupTextFunc(tPinText) ;
						}
					});
				}
				else{
					tPinText += "\n无额外信息" ;
					if( g_MapPanel_updatePinPopupTextFunc!==null){
						g_MapPanel_updatePinPopupTextFunc(tPinText) ;
					}
				}
			}//if( lyrInOlMap!==null )
		}//if( topMostLyrParams!==null ){
	}
}



//demo xyz https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png
//        isActiveGroupA={isActiveGroupA}
//        layerOrderArray={layerOrderArray}
//
//props.mtbCmd 
//props.mtbCmdVal 
//props.onMapRoiDrawEndCallback
//props.currentRoiObject  当前感兴趣区对象 rid为0时geojson为内容表示临时感兴趣区，否则geojson存放的是url
//props.appDateA
//props.appDateB
//props.openlayerRef
//props.viewProjection   : support EPSG:4326 EPSG:3857 EPSG:3413 EPSG:3976
function MapPanel(props) {

	const getMapExtent =function() {
		//result example is [31.9, 9.9, 191.78, 68.66];
		return olMap.getView().calculateExtent(olMap.getSize());
	}
	props.openlayerRef.current.getMapExtent = getMapExtent ;

	if (g_draggerCenterX < 0) {
		g_draggerCenterX = viewWidth / 2 + draggerWidth / 2;
	}

	const [olMap, setOlMap] = useState(null);
	const [roiVectorLayerSource, setRoiVectorLayerSource] = useState(null);//绘制ROI的矢量图层数据源
	const [roiVectorLayer, setRoiVectorLayer] = useState(null);//绘制ROI的矢量图层
	const [roiDraw, setRoiDraw] = useState(null);
	const [popUpClassName, setPopUpClassName] = useState('pixelvalue-popup-show') ;
	const [pinboxText, setPinboxText] = useState("none") ;


	//每次olMap添加图层完成后下面值自动加1，用于通知更新全部 datetime
	const [afterLayerAddedEventCount, setAfterLayerAddedEventCount] = useState(0);

	//const mtbCmdRef = useRef() ;


	useEffect(() => {
		g_isInSwipeCompareMode = props.isUsingSwipeMode ;
	}, [props.isUsingSwipeMode])

	useEffect(() => {
		g_MapPanel_appDateA = props.appDateA;
		g_MapPanel_appDateB = props.appDateB;
	}, [props.appDateA,props.appDateB])
	
	
	const updatePinPopupText = function(text) {
		setPinboxText(text) ;
		showPinBox() ;
	}
	g_MapPanel_updatePinPopupTextFunc = updatePinPopupText ;

	const showPinBox = function() {
		setPopUpClassName("pixelvalue-popup-show") ;
	}

	const hidePinBox = function() {
		setPopUpClassName("pixelvalue-popup-hide") ;
	}


	useEffect(() => {
		if( props.mtbCmd !== 'pin' )
		{
			hidePinBox() ;
			setPinboxText("") ;
		}
		g_MapPanel_mtbcmd = props.mtbCmd ;
	}, [props.mtbCmd])
	


	//帮助函数，用于通过 displayid 和layerOrderArray获取新的图层zIndex
	const helperFunctionForGettingLayerZIndex = function (displayid, layerOrderArray) {
		for (let i = 0; i < layerOrderArray.length; ++i) {
			if (layerOrderArray[i].displayid == displayid) {
				return i;
			}
		}
		return 0;
	}

	// private
	// 获取图层组A或者B的引用
	const helperHetOlMapGroupRef = function (tOlMap, tag) {
		if (tOlMap === null) return null;
		let tempLayers = tOlMap.getLayers().getArray();
		for (let i = 0; i < tempLayers.length; ++i) {
			const lyrItem = tempLayers[i];
			if (typeof lyrItem.tag !== 'undefined') {
				if (lyrItem.tag === tag) {
					return lyrItem;
				}
			}

		}
		return null;
	}

	//private
	//使用图层ID查找在Openlayer图层组中的图层对象
	const helperFindLayerObjInOlMapByDisplayid = function (lyrGroup, displayid) {
		if (lyrGroup.getLayers() !== null) {
			const temparr = lyrGroup.getLayers().getArray();
			for (let i = 0; i < temparr.length; ++i) {
				const lyrItem = temparr[i];
				if ( lyrItem.displayid === displayid ) {
					return lyrItem;
				}
			}
		}
		return null;
	}

	//private
	//使用图层ID查找在ParamsGroup里面的对象
	const helperFindLayerParamsInParamsGroupByDisplayid = function (paramsGroup, displayid) {
		if (paramsGroup !== null) {
			for (let i = 0; i < paramsGroup.length; ++i) {
				const lyrItem = paramsGroup[i];
				if (lyrItem.displayid === displayid) {
					return lyrItem;
				}
			}
		}
		return null;
	}



	



	//get layer index in layer Group by displayid
	const helperGetLayerIndexInLayerGroupByDisplayid = function (lyrGroup, displayid) {
		for (let i = 0; i < lyrGroup.getLayers().getArray().length; ++i) {
			if ( lyrGroup.getLayers().getArray()[i].displayid ===displayid) {
				return i;
			}
		}
		return -1;
	}


	//private 构建一个系统直接产品（pe）| 用户产品（ud） 的WMTS Layer对象
	const helperMakePEWMTSLayerObject = async function (lyrParams,datetime14) {
		const capaUrl = global.g_serverAPIRoot + "product/" + lyrParams.pid + "/wmts/WMTSCapabilities.xml";
		const parser = new WMTSCapabilities();
		let resultLayerObj = null;
		const response = await fetch(capaUrl);
		const responseText = await response.text();
		const xmlResult = parser.read(responseText);
		let options = optionsFromCapabilities(xmlResult, {
			layer: xmlResult.Contents.Layer[0].Identifier,
			matrixSet: xmlResult.Contents.Layer[0].TileMatrixSetLink[0].TileMatrixSet,
		});
		options.dimensions.datetime = datetime14 ;//ymdhms
		options.dimensions.styleid = lyrParams.styleid;
		resultLayerObj = new TileLayer({
			source: new WMTS(options),
		});
		return resultLayerObj;
	}


	//private 获取基于脚本的静态图层产品olparams
	const helperGet_PGMInfo = async function(sid,datetime1){
		const url1= global.g_serverAPIRoot + "scripts/pgminfo/?sid=" + sid + "&datetime=" + datetime1 ;
		const response = await fetch(url1) ; //GET
		const jsonObj = await response.json() ;
	   	if( typeof jsonObj !== 'undefined' && jsonObj!==null ){
			if( jsonObj.state===0 ){
				console.log(jsonObj) ;
				return JSON.parse(jsonObj.data) ;
			}else{
				return null ;
			}
		}else{
			return null ;
		}
	}

	//private 构建一个基于脚本的静态图层产品
	const helperMake_PGM_LayerObject = async function (lyrParams,datetime14) {
		const paramsObj1 = JSON.parse(lyrParams.productDisplay.params) ;
		const sid1 = paramsObj1.sid ;
		const pgminfo1 = await helperGet_PGMInfo(sid1 , datetime14) ;
		if( pgminfo1===null ){
			console.log("bad pgminfo1") ;
			let tempLayerObj1 = new TileLayer();
			return tempLayerObj1 ;
		}else{
			let tempLayerObj1 = new TileLayer({
				source: new WMS(pgminfo1.olparams)
			});
			return tempLayerObj1;
		}
	}


	//private 构建一个xyz的静态图层产品
	const helperMake_XYZ_LayerObject = function (lyrParams) {
		const paramsObj1 = JSON.parse(lyrParams.productDisplay.params) ;
		let tempLayerObj1 = new TileLayer({
			source: new XYZ(paramsObj1)
		});
		return tempLayerObj1;
	}


	//private 构建一个系统脚本产品（pes）和用户脚本(us)的WMTS Layer对象
	const helperMake_PES_WMTSLayerObject = async function (isgroupA, lyrParams, datetime14) {
		let pesParams = JSON.parse(lyrParams.productDisplay.params);
		const capaUrl = global.g_serverAPIRoot + "scripts/" + pesParams.sid + "/wmts/WMTSCapabilities.xml";
		const parser = new WMTSCapabilities();
		let resultLayerObj = null;
		const response = await fetch(capaUrl);
		const responseText = await response.text();
		const xmlResult = parser.read(responseText);
		console.log(xmlResult);
		let options = optionsFromCapabilities(xmlResult, {
			layer: xmlResult.Contents.Layer[0].Identifier,
			matrixSet: xmlResult.Contents.Layer[0].TileMatrixSetLink[0].TileMatrixSet,
		});
		options.dimensions.datetime = datetime14 ;//2022-7-14
		options.dimensions.styleid = lyrParams.styleid;
		options.dimensions.sdui = 'null';
		resultLayerObj = new TileLayer({
			source: new WMTS(options),
		});
		return resultLayerObj;
	}


	//private
	//使用图层组参数更新Openlayer的图层组
	const helperUpdateOlMapLayerGroupByParamsGroup = async function (tOlMap, groupTag, paramsGroup) {
		if (paramsGroup !== null) {
			let tempIsGroupA = true;
			if (groupTag === 'GroupB') {
				tempIsGroupA = false;
			}
			let lyrGroup = helperHetOlMapGroupRef(tOlMap, groupTag);
			//删除Params里面没有，但是OpenLayer里面有的图层
			{
				const olLayersArr = [...lyrGroup.getLayers().getArray()];
				for (let i = 0; i < olLayersArr.length; ++i) {
					const params1 = helperFindLayerParamsInParamsGroupByDisplayid(paramsGroup, olLayersArr[i].displayid);
					if (params1 === null) {
						const remindex = helperGetLayerIndexInLayerGroupByDisplayid(lyrGroup, olLayersArr[i].displayid);
						lyrGroup.getLayers().getArray().splice(remindex, 1);
					}
				}
			}
			let tempDate = props.appDateA;//Date
			if (tempIsGroupA === false) {
				tempDate = props.appDateB;//Date
			}
			const ymd14 = helperConvertJsDate2yyyyMMdd(tempDate);
			//添加或者更新Params里面有，OpenLayer里面没有或者需要更新的图层
			for (var i = 0; i < paramsGroup.length; ++i) {
				let tempLayerParams1 = paramsGroup[i];
				let olLyrObj = helperFindLayerObjInOlMapByDisplayid(lyrGroup, tempLayerParams1.displayid);
				if (olLyrObj === null) {//在openlayer里没有，需要新加这个图层 ///////////////////////////////////////////////////////////// IMPORTANT 添加新图层
					if (tempLayerParams1.productDisplay.type === 'wms') {
						//图层类型是wms
						const tempDisplayParams = JSON.parse(tempLayerParams1.productDisplay.params);
						let tempLayerObj1 = new TileLayer({
							source: new WMS({
								url: tempDisplayParams.url,
								params: tempDisplayParams.params
							})
						});
						tempLayerObj1.displayid = tempLayerParams1.displayid;
						tempLayerObj1.setZIndex(tempLayerParams1.zindex);
						tempLayerObj1.setOpacity(tempLayerParams1.opacity);
						lyrGroup.getLayers().getArray().push(tempLayerObj1);
						olLyrObj = tempLayerObj1;
					}
					else if(tempLayerParams1.productDisplay.type === 'xyz'){
						let tempLayerObj1 = helperMake_XYZ_LayerObject(tempLayerParams1) ;
						tempLayerObj1.displayid = tempLayerParams1.displayid;
						tempLayerObj1.setZIndex(tempLayerParams1.zindex);
						tempLayerObj1.setOpacity(tempLayerParams1.opacity);
						lyrGroup.getLayers().getArray().push(tempLayerObj1);
						olLyrObj = tempLayerObj1;
					}
					else if (tempLayerParams1.productDisplay.type === 'pe'
						|| tempLayerParams1.productDisplay.type === 'ud'
					) {
						//系统直接产品图层
						let tempLayerObj1 = await helperMakePEWMTSLayerObject(tempLayerParams1,ymd14);//2022-7-17
						tempLayerObj1.displayid = tempLayerParams1.displayid;
						tempLayerObj1.setZIndex(tempLayerParams1.zindex);
						tempLayerObj1.setOpacity(tempLayerParams1.opacity);
						lyrGroup.getLayers().getArray().push(tempLayerObj1);
						olLyrObj = tempLayerObj1;
					} else if (
						tempLayerParams1.productDisplay.type === "pes"
						|| tempLayerParams1.productDisplay.type === "us"
						) {
						//系统脚本产品 和 用户脚本
						let tempLayerObj1 = await helperMake_PES_WMTSLayerObject(
							tempIsGroupA, tempLayerParams1, ymd14);//2022-7-17
						tempLayerObj1.displayid = tempLayerParams1.displayid;
						tempLayerObj1.setZIndex(tempLayerParams1.zindex);
						tempLayerObj1.setOpacity(tempLayerParams1.opacity);
						lyrGroup.getLayers().getArray().push(tempLayerObj1);
						olLyrObj = tempLayerObj1;
					} else if( tempLayerParams1.productDisplay.type==='pgm'){
						//2022-7-17
						let tempLayerObj1 = await helperMake_PGM_LayerObject( tempLayerParams1, ymd14);
						tempLayerObj1.displayid = tempLayerParams1.displayid;
						tempLayerObj1.setZIndex(tempLayerParams1.zindex);
						tempLayerObj1.setOpacity(tempLayerParams1.opacity);
						lyrGroup.getLayers().getArray().push(tempLayerObj1);
						olLyrObj = tempLayerObj1;
					}
				} else {
					//找到这个图层了，查看是否需要调整zindex ///////////////////////////////////////////////////////////// IMPORTANT 已有图层更新参数
					if (olLyrObj.getZIndex() !== tempLayerParams1.zindex) {
						olLyrObj.setZIndex(tempLayerParams1.zindex);
					}
					//找到这个图层，查看是否修改可见属性
					if (olLyrObj.getVisible() !== tempLayerParams1.visible) {
						olLyrObj.setVisible(tempLayerParams1.visible);
					}
					//透明度
					if (olLyrObj.getOpacity() !== tempLayerParams1.opacity) {
						olLyrObj.setOpacity(tempLayerParams1.opacity);
					}

					if (tempLayerParams1.productDisplay.type === 'pe'
						|| tempLayerParams1.productDisplay.type === 'ud'
					) {
						//渲染方案更新
						let newDims = {};
						newDims.datetime = ymd14 ;
						newDims.styleid = tempLayerParams1.styleid;
						olLyrObj.getSource().updateDimensions(newDims);
					}
					else if (tempLayerParams1.productDisplay.type === "pes"
					|| tempLayerParams1.productDisplay.type === "us") {
						//更新sdui 与其他dimensions styleid datetime
						let newDims = {};
						newDims.datetime = ymd14 ;
						newDims.styleid = tempLayerParams1.styleid;
						newDims.sdui = 'null';
						if(tempLayerParams1.productDisplay.type === "us"){
							newDims.utime = tempLayerParams1.utime ;
						}
						if (typeof tempLayerParams1.sdui !== 'undefined' && tempLayerParams1.sdui !== null) {
							let slimSdui = {};
							for (let key in tempLayerParams1.sdui) {
								slimSdui[key] = { val: tempLayerParams1.sdui[key].val };
							}
							newDims.sdui = JSON.stringify(slimSdui);
						}
						olLyrObj.getSource().updateDimensions(newDims);
					}else if( tempLayerParams1.productDisplay.type === "pgm"){
						//2022-7-17 更新图层源对象
						const paramsObj1 = JSON.parse(tempLayerParams1.productDisplay.params) ;
						const sid1 = paramsObj1.sid ;
						const pgminfo1 = await helperGet_PGMInfo(sid1 , ymd14) ;
						if( pgminfo1===null ){
							console.log("bad pgminfo1") ;
							return  ;
						}else{
							olLyrObj.setSource(new WMS(pgminfo1.olparams)) ;
						}					
					}
				}
				//卷帘的回调函数
				if (olLyrObj !== null) {
					if (props.isUsingSwipeMode === true) {
						if (groupTag === 'GroupA') {
							olLyrObj.on('prerender', g_onGroupAPrerenderCallback);
							olLyrObj.on('postrender', g_onGroupAPostrenderCallback);
						} else if (groupTag === 'GroupB') {
							olLyrObj.on('prerender', g_onGroupBPrerenderCallback);
							olLyrObj.on('postrender', g_onGroupBPostrenderCallback);
						}
					} else {
						if (groupTag === 'GroupA') {
							olLyrObj.un('prerender', g_onGroupAPrerenderCallback);
							olLyrObj.un('postrender', g_onGroupAPostrenderCallback);
						} else if (groupTag === 'GroupB') {
							olLyrObj.un('prerender', g_onGroupBPrerenderCallback);
							olLyrObj.un('postrender', g_onGroupBPostrenderCallback);
						}
					}
				}
			}
		}
	}


	//绘图完成
	const onDrawEndCallback = function (draw) {
		setRoiDraw(null);
		const tempGeojson = new GeoJSON().writeFeature(draw.feature, { decimals: 5 });
		olMap.removeInteraction(draw.target);
		global.g_temporyRoiIndex = global.g_temporyRoiIndex + 1;
		const tname = "临时感兴趣区" + global.g_temporyRoiIndex.toString();

		let tempRoi = { rid: 0, name: tname, geojson: tempGeojson, from: props.mtbCmd };//from 这里用于区分通过rect或者poly命令绘制的ROI
		props.onMapRoiDrawEndCallback(tempRoi);
	}



	// 根据图层参数数组修改Openlayer图层和图层的顺序
	useEffect(async () => {
		var tempMap = null;
		if (olMap == null) {
			let lyrGroupA = new LayerGroup({});
			lyrGroupA.tag = "GroupA";
			let lyrGroupB = new LayerGroup({});
			lyrGroupB.tag = "GroupB";

			g_MapPanel_olMapLayerGroupA = lyrGroupA ;
			g_MapPanel_olMapLayerGroupB = lyrGroupB ;

			//绘制ROI的矢量图层
			const tempVecSource = new VectorSource({ wrapX: false });
			const tempVecLayer = new VectorLayer({ 
				source: tempVecSource, 
				zIndex: 999999 , 
				style: new Style({
					fill:new Fill(
						{
							color: 'rgba(255, 255, 255, 0.2)',
						}
					) ,
					stroke: new Stroke({
						color: '#ffcc33',
						width: 2,
					})
				})
			 });
			setRoiVectorLayerSource(tempVecSource);
			setRoiVectorLayer(tempVecLayer);
			const origProjection = getProjection( (props.viewProjecton!=='undefined')?props.viewProjection:"EPSG:4326" ) ;
			const origExtent = origProjection.getExtent() ;
			console.log("debug origProjection "+props.viewProjecton) ;
			console.log(origProjection) ;
			tempMap = new Map({
				controls: [],
				target: 'map',
				layers: [lyrGroupA, lyrGroupB, tempVecLayer],
				view: new View({
					projection: origProjection ,
					center: [0, 0],
					multiWorld:true,
					zoom: 0,
					extent: undefined , 
					minZoom:0,
					maxZoom:20,
					constrainResolution:true,
					smoothResolutionConstraint:true,
				})
			});

			
			const pos = fromLonLat([18.47561 ,-34.35669],'EPSG:4326');
			const pixelValuePopup = new Overlay({
				position: pos,
				element: document.getElementById('pixelvalue-popup'),
				positioning:'bottom-center',
			  });
			g_MapPanel_pinboxOverlay = pixelValuePopup ;
			tempMap.addOverlay(pixelValuePopup); 
			tempMap.on('singleclick', g_onMapSingleClickedFunc ) ;
			setOlMap(tempMap);
			g_MapPanel_olMap = tempMap ;
		} else {
			tempMap = olMap;
		}
		await helperUpdateOlMapLayerGroupByParamsGroup(tempMap, 'GroupB', props.groupB);
		await helperUpdateOlMapLayerGroupByParamsGroup(tempMap, 'GroupA', props.groupA);
		tempMap.render();
		//添加图层完成
		setAfterLayerAddedEventCount(afterLayerAddedEventCount + 1);

		g_MapPanel_groupAArray = props.groupA ;
		g_MapPanel_groupBArray = props.groupB ;
	}, [props.groupA, props.groupB, props.isUsingSwipeMode
	,props.appDateA,props.appDateB])


	//卷帘效果拖拽控件事件函数
	const onDraggerDraggedCallback = function (event, data) {
		//如果开启了卷帘效果，使用context绘制GroupA和GroupB
		if (props.isUsingSwipeMode) {
			g_draggerCenterX = data.x + draggerWidth / 2;
			olMap.render();
		}
	}


	//private
	//将Javascript Date对象转换成 yyyyMMdd000000 格式 , HHmmss使用0填充
	const helperConvertJsDate2yyyyMMdd = function (dateObj) {
		let ymd14 = dateObj.getFullYear() * 10000;
		ymd14 += (dateObj.getMonth() + 1) * 100;
		ymd14 += dateObj.getDate();
		ymd14 = ymd14 * 1000000;
		return ymd14;
	}


	//主工具栏命令响应
	useEffect(() => {
		if (olMap !== null) {
			if (props.mtbCmd === 'roi') {

			} else if (props.mtbCmd === 'zin') {
				const tempZoom = olMap.getView().getZoom();
				olMap.getView().setZoom(tempZoom + 1);
			} else if (props.mtbCmd === 'zout') {
				const tempZoom = olMap.getView().getZoom();
				olMap.getView().setZoom(tempZoom - 1);
			} else if (props.mtbCmd === 'pan') {
				//平移模式，移除绘图
				if (roiDraw !== null) {
					olMap.removeInteraction(roiDraw);
					setRoiDraw(null);
				}
			} else if (props.mtbCmd === 'rect') {
				roiVectorLayerSource.clear();
				let tempDraw = new Draw({
					source: roiVectorLayerSource,
					type: 'Circle',
					geometryFunction: createBox(),
				});
				tempDraw.on('drawend', onDrawEndCallback);
				setRoiDraw(tempDraw);
				olMap.addInteraction(tempDraw);
			} else if (props.mtbCmd === 'poly') {
				roiVectorLayerSource.clear();
				let tempDraw = new Draw({
					source: roiVectorLayerSource,
					type: 'Polygon',
				});
				tempDraw.on('drawend', onDrawEndCallback);
				setRoiDraw(tempDraw);
				olMap.addInteraction(tempDraw);
			} else if (props.mtbCmd === 'coor') {
				//切换视图坐标系命令
				console.log("debug new proj " + props.viewProjection) ;
				const newProj = getProjection( props.viewProjection ) ;
				console.log("debug get projection:") ;
				console.log(newProj) ;
				g_MapPanel_olMap.setView(new View({
					projection: newProj,
					center: [0, 0],
					zoom: 1,
					minZoom:0,
					extent: undefined
				  }));
			}
			else if (props.mtbCmd === 'clear') {
				roiVectorLayerSource.clear();
			}
		}
	}, [props.mtbCmd, props.mtbCmdVal]);



	//绘制当前感兴趣区 ROI
	useEffect(() => {
		if (roiVectorLayerSource !== null) {
			roiVectorLayerSource.clear();
			if (props.currentRoiObject !== null) {
				if (props.currentRoiObject.rid > 0) {
					//服务器端ROI
					console.log("props.currentRoiObject.rid > 0");
					//拉取远程ROI nginx url
					const geojsonUrl = global.g_staticResourceRoot + props.currentRoiObject.geojson;
					console.log(geojsonUrl);
					fetch(geojsonUrl)
						.then(response => response.json())
						.then((geojsonData) => {
							const tempFeatures = new GeoJSON().readFeatures(geojsonData);
							roiVectorLayerSource.addFeatures(tempFeatures);
						});
				} else {
					//浏览器临时ROI
					const tempFeature = new GeoJSON().readFeature(props.currentRoiObject.geojson);
					roiVectorLayerSource.addFeature(tempFeature);
				}
			}
		}
	}, [props.currentRoiObject]);




	return (
		<>
			<div id='map'>
			</div>
			{
				(props.isUsingSwipeMode) ? (
					<Draggable axis="x"
						defaultPosition={{ x: g_draggerCenterX - 28, y: 790 }}
						bounds={{ left: 20, top: 20, right: viewWidth - 20 - draggerWidth, bottom: viewHeight - 20 - draggerHeight }}
						onDrag={onDraggerDraggedCallback} >
						<div id="MapPanelDragger" style={{ backgroundImage: `url("/images/swipe-dragger.png")` }} >
							<div>A</div>
							<div>B</div>
						</div>
					</Draggable>
				) : ""
			}
			<div style={{display: 'none'}}>
	      		{/* Popup */}
    			<div id="pixelvalue-popup"
				className={popUpClassName}
				>
					<div className="pixelvalue-popup-container">
						<textarea rows = "5" 
						readOnly
						className="pinbox-text-area"
						value={pinboxText}>
						</textarea>
					</div>
					<div className="pixelvalue-popup-tail">&nbsp;</div>
				</div>
    		</div>
		</>

	)
}

export default MapPanel
